// axios封装处理
// 
import axios from 'axios'
// 1.根域名
const request = axios.create({
  //根域名
  baseURL: 'http://192.168.1.100:80',
  // baseURL: 'http://localhost:3004'
  // 超时时间
  timeout: 30000
})

// 2.添加请求拦截器
request.interceptors.request.use((config) => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
}, (error) => {
  // 错误处理
  return Promise.reject(error);
})

// 3.响应拦截器
request.interceptors.response.use((response) => {
  // 2xx 范围内的状态码都会触发该函数。
  // 对响应数据做点什么
  return response.data;
}, (error) => {
  // 超出 2xx 范围的状态码都会触发该函数。
  // 对响应错误做点什么
  // 监控401 token过期
  if (error.response && error.response.status === 401) {
    // 清除token
    localStorage.removeItem('token');
    // 跳转到登录页面
    window.location.href = '/login';
  }
  return Promise.reject(error);
})

// 添加登录请求方法
const login = async (username, password, role) => {
  
  
  try {
    console.log('开始登录请求');
    const response = await request.post('/api/login', {
      username,
      password,
      role
    });
    console.log('登录请求成功');
    return response;
  } catch (error) {
    console.error('登录请求出错:', error);
    throw error;
  }
};
const getUsers = async (role) => {
  try {
    console.log('开始获取用户数据');
    
    const response = await request.get('/api/users', {
      params: { role }
    });
    console.log('开始获取用户数据');
    return response.data.map((item, index) => ({
      key: index,
      id: item._id ,
      username: item.username,
      email: item.email,
      joinDate: item.createdAt || '2023-01-01',
      role: 'user'
    }));
  } catch (error) {
    console.error('获取用户数据出错:', error);
    throw error;
  }
};

const getAdmins = async (role) => {
  try {
    console.log('开始获取用户数据');
    
    const response = await request.get('/api/admins', {
      params: { role }
    });
    console.log('开始获取用户数据');
    return response.data.map((item, index) => ({
      key: index,
      id: item._id ,
      username: item.username,
      email: item.email,
      joinDate: item.createdAt || '2023-01-01',
      role: 'admin'
    }));
  } catch (error) {
    console.error('获取用户数据出错:', error);
    throw error;
  }
};



// 新增表单提交函数

const addUser = async (userData) => {
  try {
      const response = await request.post('/api/users', userData);
      return response;
  } catch (error) {
      console.error('添加用户出错:', error);
      throw error;
  }
};

const deleteUser = async (id) => {
  try {
    const response = await request.delete(`/api/users/${id}`);
    return response;
  } catch (error) {
    console.error('删除用户出错:', error);
    throw error;
  }
};

const addAdmin = async (adminData) => {
  try {
    const response = await request.post('/api/admins', adminData);
    return response;
  } catch (error) {
    console.error('添加管理员出错:', error);
    throw error;
  }
};

export {request, login, getUsers, getAdmins, addUser, deleteUser,addAdmin};
